import React, { Component } from 'react';
import moment from 'moment';  //time格式工厂
import style from './RoleManage.less';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import PageHeaderWrapper from '@/components/PageHeaderWrapper';  //头部的那个版块的东西
import ModalBox from './ModalBox';
import UpdatePermssion from './UpdatePermssion';
import UpdateNoRoute from './UpdateNoRoute';
import DetailsModel from './DetailsModel';
import PageLoading from '@/components/PageLoading'
import {
  Button,
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Table,
  Modal,
  Select,
  Card,
  PageHeader,
  Alert,
  Pagination,
  message,
  Icon,
  Spin,
  Divider, Empty,
} from 'antd';


//日期插件
const { MonthPicker, RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

//表单
const FormItem = Form.Item;

//所属租户选择框
const Option = Select.Option;


//页头&&面包屑
const routes = [
  {
    path: 'index',
    breadcrumbName: 'First-level Menu',
  },
  {
    path: 'first',
    breadcrumbName: 'Second-level Menu',
  },
  {
    path: 'second',
    breadcrumbName: 'Third-level Menu',
  },
];


//命名空间
const namespace = 'RoleManage';

const mapStateToProps = function(state) {
  const dataSource = state[namespace].dataSource;
  return {
    dataSource: dataSource,   //全部数据
    dataList: dataSource ? dataSource.data.list : [],   //专门给表格使用的
    total_elements: dataSource ? dataSource.total_elements : 0,    //总记录数
    loading: state.loading.models.RoleManage,
    nowDetails : state[namespace].nowDetails,
    datailsState : state[namespace].datailsState,
    updateModalProps:{
      platformHalfCheckMap: state[namespace].platformHalfCheckMap,
      updateVisible : state[namespace].updateVisible,
      updateData:state[namespace].updateData,
      platformData:state[namespace].platformData,
      platformPermissMap:state[namespace].platformPermissMap,
      platformRoleMap:state[namespace].platformRoleMap,

    },
    updateNoRouteProps : {
      noRoutePlatformRoleMap : state[namespace].noRoutePlatformRoleMap,
      noRouteUpdateVisible:state[namespace].noRouteUpdateVisible,
      noRoutePlatformPermissMap:state[namespace].noRoutePlatformPermissMap,
      noRoutePlatformData:state[namespace].noRoutePlatformData,
      noRouteUpdateData:state[namespace].noRouteUpdateData,
    }
  };

};

const mapDispatchToProps = function(dispatch) {
  return {
    dispatch: dispatch,
  };
};


@connect(mapStateToProps, mapDispatchToProps)
@Form.create()
class RoleManage extends Component {

  componentDidMount() {

    //页面加载前申请一次内容
    const mountLoad = {
      page_size: 10,
      page_num: 1,
    };
    const action = {
      type: `${namespace}/selectBegin`,
      payload: mountLoad,
    };

    const { dispatch } = this.props;
    dispatch(action);


  }

  state = {
    //分页相关状态
    page_size: 10,
    page_num: 1,
    //模态框相关状态
    visible: false,
    //编辑内容状态
    nowRow: null,

    //权限树状态
    permission_tree: null,
    //权限内容
    permissionIdNow: [],
    //搜索表单状态
    searchFormNow: null,

  };

  //新增后，将state中的页码状态复位 清空搜索表单状态
  clearSearchForm = () => {
    this.setState({
      page_num: 1,
      searchFormNow: null,
    });
    //清空表单
    this.clearNow();

  };

  //父组件操作子组件清空的方法
  onRef = (ref) => {
    this.child = ref;
  };

  clearNow = (e) => {
    this.child.handleReset();
  };


  //查看详情
  detailsList(values) {
    const role_id = values.role_id;
    this.props.dispatch({
      type: `${namespace}/detailsSearch`,
      payload: {
        role_id: role_id,
      },
      callback: (res) => {
        this.props.dispatch({
          type: `${namespace}/save`,
          payload: {
            datailsState: true,
            nowDetails:res
          }
        })

      },
    });

    this.setState({
      nowRow: values,
    });
  }

  //关闭详情模态框
  closeDatails = () => {
    this.saveState({datailsState: false ,nowDetails :undefined})

  };

  //删除处理
  deleteList(id) {
    const props = this.props;
    const _this = this;
    Modal.confirm({
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      okText: '确认',
      cancelText: '取消',
      icon: 'frown',
      onOk() {
        //发送删除请求
        props.dispatch({
          type: `${namespace}/deleteBegin`,
          payload: {
            role_id: id,
          },
          callback: (res) => {
            if (res.return_code === 'SUCCESS') {
              message.success('删除成功');
            }
            //代入当前分页状态重新查询一次
            props.dispatch({
              type: `${namespace}/selectBegin`,
              payload: {
                page_size: _this.state.page_size,
                page_num: _this.state.page_num,
                ..._this.state.searchFormNow,
              },
            });
          },
        });

      },
      onCancel() {
        return false;
      },
    });

  }

  //子模态框组件修改state保持模态框关闭方法
  childModalChangeModalState() {
    this.setState({
      visible: false,
    });
  }

  //关闭-模态框
  hideCancel = () => {
    this.setState({ visible: false });
  };

  //显示-模态框
  showModal = () => {
    this.setState({
      visible: true,
    });
  };





  //搜索时重置分页页数的方法
  changePage = (values) => {
    //把分页条件放入state
    this.setState({
      searchFormNow: values,
    });
    this.setState({
      page_num: 1,
    });
  };

  //设置权限方法
  setSystem = (values,type) => {
    if(type === 'route'){
      this.props.dispatch({
        type: `${namespace}/showUpdatePermssionModal`,
        payload: {
          role_id : values.role_id
        },
      });
    }else if (type === 'noRoute'){
      this.props.dispatch({
        type: `${namespace}/showUpdateNoRoute`,
        payload: {
          role_id : values.role_id
        },
      });
    }

  };
  updatePermssion =(values)=>{
    this.props.dispatch({
      type: `${namespace}/editBegin`,
      payload: {
        ...values
      },
    }).then((r)=>{
      if(r){
        this.props.dispatch({
          type: `${namespace}/save`,
          payload: {
            updateVisible :false,
            updateData:undefined,
            platformData:undefined,
            platformPermissMap:undefined, // 平台对应角色的集合 { '平台名' : [ {....权限数据}] }
            platformRoleMap:undefined,// 平台对应角色的集合 { '平台名' : [ '该角色的功能点', '该角色的功能点', '该角色的功能点', '该角色的功能点'] }
            platformHalfCheckMap:undefined
          },
        });
      }
    });
  }
  updateNoRoutePermssion =(values)=>{
    this.props.dispatch({
      type: `${namespace}/editBegin`,
      payload: {
        ...values
      },
    }).then((r)=>{
      if(r){
        this.props.dispatch({
          type: `${namespace}/save`,
          payload: {
            noRouteUpdateVisible :false,
            noRoutePlatformData:undefined,
            noRoutePlatformPermissMap:undefined, // 平台对应角色的集合 { '平台名' : [ {....权限数据}] }
            noRoutePlatformRoleMap:undefined,// 平台对应角色的集合 { '平台名' : [ '该角色的功能点', '该角色的功能点', '该角色的功能点', '该角色的功能点'] }
          },
        });
      }
    });
  }
  noRouteFindPermissByPlatform =(values,role_id) =>{
    this.props.dispatch({
      type: `${namespace}/findNoRoutePermissByPlatform`,
      payload: {
        platformList : values,
        role_id  : role_id
      },
    });
  }
  findPermissByPlatform =(values,role_id) =>{
    this.props.dispatch({
      type: `${namespace}/findPermissByPlatform`,
      payload: {
        platformList : values,
        role_id  : role_id
      },
    });
  }
  closeUpdateModel = ()=>{
    this.props.dispatch({
      type: `${namespace}/save`,
      payload: {
        updateVisible :false,
        platformData:undefined,
        platformPermissMap:undefined, // 平台对应角色的集合 { '平台名' : [ {....权限数据}] }
        platformRoleMap:undefined,// 平台对应角色的集合 { '平台名' : [ '该角色的功能点', '该角色的功能点', '该角色的功能点', '该角色的功能点'] }
        platformHalfCheckMap:undefined
      },
    });
  }
  closeNoRouteUpdateModel = ()=>{

    this.props.dispatch({
      type: `${namespace}/save`,
      payload: {
        noRouteUpdateVisible :false,
        noRoutePlatformData:undefined,
        noRoutePlatformPermissMap:undefined, // 平台对应角色的集合 { '平台名' : [ {....权限数据}] }
        noRoutePlatformRoleMap:undefined,// 平台对应角色的集合 { '平台名' : [ '该角色的功能点', '该角色的功能点', '该角色的功能点', '该角色的功能点'] }
      },
    });
  }
  saveState = (values)=>{
    this.props.dispatch({
      type: `${namespace}/save`,
      payload: {
        ...values
      },
    });
  }
  //表格分页监听函数
  tableChange = (pagination, filters, sorter) => {

    const lastSearch = {
      ...this.props.dataSource.searchQ,
    };

    //这个步骤是为了在有查询条件的时候不会丢掉查询条件
    const params = {
      ...this.props.dataSource.searchQ,
      page_num: pagination.current,
      page_size: pagination.pageSize,
    };

    const action = {
      type: `${namespace}/selectBegin`,
      payload: params,
    };
    const { dispatch } = this.props;
    dispatch(action);

  };

  render() {
    const { pagination,loading ,
          updateModalProps : {
            updateVisible,
            updateData,
            platformData,
            platformPermissMap,
            platformRoleMap,
            platformHalfCheckMap,
          },
          updateNoRouteProps
    } = this.props;

    //列  列名
    const columns = [

      {
        title: formatMessage({ id: 'iot.roleManage.roleManage_list.role_name' }),
        dataIndex: 'role_name',
        align: 'center',
        render: (text, record) => {
          return (
            <a onClick={() => this.detailsList(record)}>{record.role_name}</a>
          );
        },
      },
      {
        title: formatMessage({ id: 'iot.roleManage.roleManage_list.create_user_id' }),
        dataIndex: 'create_user_name',
        align: 'center',
      },
      {
        title: formatMessage({ id: 'iot.roleManage.roleManage_list.create_time' }),
        dataIndex: 'create_time',
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'doIt',
        key: 'doIt',
        render: (text, record) => (
          <span className="table-operation">
               <a onClick={() => this.deleteList(record.role_id)}>
               删除
              </a>
              <Divider type="vertical"/>
              <a onClick={() => this.setSystem(record,'route')}>设置页面权限</a>
              <Divider type="vertical"/>
              <a onClick={() => this.setSystem(record,'noRoute')}>设置非页面权限</a>
            </span>
        ),
        align: 'center',
      },
    ];


    //分页配置项
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: Number(this.props.dataSource ? this.props.dataSource.data.total_elements : 0), //读取总数据数
      current: Number(this.props.dataSource ? this.props.dataSource.data.page_num : 1),  //当前页数
      showTotal: (total) =>
        `共有 ${parseInt(total)} 条数据 当前第${this.state.page_num}页`,
      onChange: (page, pageSize) => {
        this.setState({
          page_num: page,
          page_size: pageSize,
        });
      },
      onShowSizeChange: (current, size) => {
        this.setState({
          page_num: current,
          page_size: size,
        });
      },
      ...pagination,
    };

    return (
      <PageHeaderWrapper>
        <Spin spinning={!this.state.visible && !updateVisible && !this.props.datailsState && loading ?true :false}>
           <div
              style={{
                backgroundColor: '#FFFFFF',
                paddingLeft: '5%',
                paddingRight: '5%',
              }}
          >
          {/* 查询表单部分 */}
          <TheNewForm
            dispatch={this.props.dispatch}
            showModal={this.showModal}
            changePage={this.changePage}
            onRef={this.onRef}
          />
          {/* 渲染列表部分 */}
          {
            this.props.dataList && this.props.dataList.length > 0 ?
              <Table
                dataSource={this.props.dataList}
                columns={columns}
                rowKey={record => record.role_id}
                onChange={this.tableChange}
                pagination={paginationProps}
                onShowSizeChange={this.onShowSizeChange}
              />
              :
              <Empty
                style={{ paddingBottom: 30, paddingTop: 15 }}
              />
          }
          {/* 模态框部分 */}
          {this.state.visible ?
            <ModalBox
              showModal={this.showModal}

              hideCancel={this.hideCancel}
              visible={this.state.visible}
              childModalChangeModalState={this.childModalChangeModalState.bind(this)}
              page_num={this.state.page_num}
              page_size={this.state.page_size}
              clearSearchForm={this.clearSearchForm}
              searchFormNow={this.state.searchFormNow}
            /> :
            []
          }
          {/* 设置权限模态框 */}
          {
            updateVisible ?
              <UpdatePermssion
                visible = {updateVisible}
                modalHandleOk={this.updatePermssion}
                updateData= {updateData}
                platformData = {platformData}
                platformHalfCheckMap={platformHalfCheckMap}
                loading = {loading}
                modalHandleCancel = {this.closeUpdateModel}
                findPermissByPlatform={this.findPermissByPlatform}
                platformPermissMap={platformPermissMap}
                platformRoleMap={platformRoleMap}
                saveState={this.saveState}
              />
              : []
          }
          {
             updateNoRouteProps.noRouteUpdateVisible ?
               <UpdateNoRoute
                 visible = {updateNoRouteProps.noRouteUpdateVisible}
                 modalHandleOk={this.updateNoRoutePermssion}
                 updateData= {updateNoRouteProps.noRouteUpdateData}
                 platformData = {updateNoRouteProps.noRoutePlatformData}
                 loading = {loading}
                 modalHandleCancel = {this.closeNoRouteUpdateModel}
                 findPermissByPlatform={this.noRouteFindPermissByPlatform}
                 platformPermissMap={updateNoRouteProps.noRoutePlatformPermissMap}
                 platformRoleMap={updateNoRouteProps.noRoutePlatformRoleMap}
                 saveState={this.saveState}
               />
               : []
           }

          {/* 详情模态框 */}
             {
               this.props.datailsState?
                 <DetailsModel
                   datailsState={this.props.datailsState}
                   closeDatails={this.closeDatails}
                   nowDetails={this.props.nowDetails}
                 /> :
                 []
             }

        </div>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default RoleManage;

//创建高阶表单组件
class NewForm extends Component {
  componentDidMount() {
    this.props.onRef(this);
  }

  //表单重置
  handleReset = () => {
    this.props.form.resetFields();
  };

  //查询表单方法
  query = e => {
    const { dispatch } = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const valuesEnd = {
          'page_size': 10,
          'page_num': 1,
        };
        if (values.role_name) {
          valuesEnd.role_name = values.role_name;
        }
        if (values.create_time && values.create_time.length > 0) {
          valuesEnd.created_time_from = moment(values.create_time[0]).format('YYYY-MM-DD HH:mm:ss');
          valuesEnd.created_time_to = moment(values.create_time[1]).format('YYYY-MM-DD HH:mm:ss');
        }
        this.props.changePage(values);
        dispatch({
          type: `${namespace}/selectBegin`,
          payload: valuesEnd,
        });
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    //规则就是用来打破的
    const role_name_rules = {
      rules: [
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能输入空格',
        },
      ],
    };
    const createTime_rules = {
      rules: [],
    };
    const tenant_rules = {
      // initialValue: null,
    };

    return (
      /*查询表单部分*/
      <Form onSubmit={this.query} layout="inline">
        <div
          style={{
            fontSize: '16px',
            marginBottom: '15px',
          }}
        >
          <div style={{ height: 60 }}>
            <Row align="middle">
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>{formatMessage({ id: 'iot.roleManage.roleManage_list.role_name' })} :
                </div>
                {getFieldDecorator('role_name')(
                  <Input placeholder="请输入" style={{ width: '65%' }}/>,
                )}
              </Col>
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>{formatMessage({ id: 'iot.roleManage.roleManage_list.create_time' })} :
                </div>
                {getFieldDecorator('create_time')(
                  <RangePicker
                    placeholder={['开始日期', '结束日期']}
                    showTime={{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }}
                    format="YYYY-MM-DD HH:mm:00"
                    onChange={this.queryCreate}
                    style={{ width: '65%' }}
                  />,
                )}
              </Col>
            </Row>
          </div>
          <div style={{ height: '40px', fontSize: '16px' }}>
            <Row gutter={30}>
              <Col md={18} sm={24} align="left" style={{ paddingLeft: 10 }}>
                  <span>
                      <Button type="primary" onClick={this.props.showModal}>新建</Button>
                   </span>
              </Col>
              <Col md={6} sm={24} align="right" style={{ paddingLeft: 10 }}>
                  <span>
                    <Button type="primary" htmlType="submit">查询</Button>
                    <Button className={style['but-type']} htmlType="reset" onClick={this.handleReset}>重置</Button>
                  </span>
              </Col>
            </Row>
          </div>
        </div>
      </Form>
    );
  }
}

const TheNewForm = Form.create({ name: 'time_related_controls' })(NewForm);
